﻿/**
* File: XmglxmxxpcService.cs
* Author: 汪杰
* Create Time:2025/2/26 13:31:08
* Email:15200358008@139.com
* 代码由TMCodeGenerator自动生成
**/
using AutoMapper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JSLCloud.Attributes;
using JSLCloud.App.Models.Xmglxmxxpc;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.SqlSugar;
using JSLCloud.Utilities.WebApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Text;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;


namespace JSLCloud.App.Mes.Service
{
    /// <summary>
    /// IXmglxmxxpcService 实现类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped,typeof(IXmglxmxxpcService))]
    public class XmglxmxxpcService : IXmglxmxxpcService
    {
        private readonly IDbContext _db;//数据库操作实例对象
        private readonly ILogger<XmglxmxxpcService> _log;//日志操作实例对象
        private readonly IMapper _mapper;//AutoMapper实例
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public XmglxmxxpcService(IDbContext dbContext, ILogger<XmglxmxxpcService> logger,IMapper mapper)
        {
            _db = dbContext;
            _log = logger;
            _mapper = mapper;
        }
        
        /// <summary>
        /// 获取xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmglxmxxpcQueryModel>>> GetAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxpcQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxpcDbModel,XmglxmxxlcDbModel>(
                    (t,t1) => new object[]
                    {
                        JoinType.Left , t.Xmlcid == t1.ID
                    });
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                
                //查询未删除数据
                query.Where("t.DELETEFLAG = 0");
                
                //排序条件
                if(requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc" 
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }
                
                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
						(t,t1) => new XmglxmxxpcQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Xmid = t.Xmid,
							Xmlcid = t.Xmlcid,
							Shyid = t.Shyid,
							Shy = t.Shy,
							Kssj = t.Kssj,
							Jssj = t.Jssj,
							Rt = t.Rt,
                            Lcmc = t1.Lcmc
						})
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
						(t,t1) => new XmglxmxxpcQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Xmid = t.Xmid,
							Xmlcid = t.Xmlcid,
							Shyid = t.Shyid,
							Shy = t.Shy,
							Kssj = t.Kssj,
							Jssj = t.Jssj,
							Rt = t.Rt,
                            Lcmc = t1.Lcmc
						})
                        .ToListAsync();
                }
                    
                //返回执行结果
                return ResponseUtil<List<XmglxmxxpcQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmglxmxxpcQueryModel>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 获取xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<dynamic>> GetCalendarAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxpcQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxpcDbModel>();
                var firstDayOfMonth = Convert.ToDateTime($"{requestObject.QueryConditions[0].Content}-01");
                var min = 1 - (int)firstDayOfMonth.DayOfWeek ;
                if ((int)firstDayOfMonth.DayOfWeek == 0) 
                {
                    min = -6;
                }

                var max = 42+min;
                var dayList = new List<string>();
                for (int i = min; i < max; i++)
                {
                    dayList.Add($"{firstDayOfMonth.AddDays(i):yyyy-MM-dd}");
                }


                //查询未删除数据
                query.Where("DELETEFLAG = 0");



                query.Where($"(kssj >= '{dayList[0]}' or jssj <= '{dayList[41]}')");
                query.OrderBy($"kssj asc");


                queryData = await query.Select(
                    (t) => new XmglxmxxpcQueryModel
                    {
                        ID = t.ID,
                        Createid = t.Createid,
                        Createname = t.Createname,
                        Createtime = t.Createtime,
                        Updateid = t.Updateid,
                        Updatename = t.Updatename,
                        Updatetime = t.Updatetime,
                        Deleteflag = t.Deleteflag,
                        Xmid = t.Xmid,
                        Xmlcid = t.Xmlcid,
                        Shyid = t.Shyid,
                        Shy = t.Shy,
                        Kssj = t.Kssj,
                        Jssj = t.Jssj,
                        Rt = t.Rt,
                    })
                    .ToListAsync();


                var dic = new Dictionary<string, List<string>>();
                foreach (var item in queryData)
                {
                    for (DateTime n = item.Kssj; n <= item.Jssj; n = n.AddDays(1))
                    {
                        if (dic.ContainsKey(n.ToString("yyyy-MM-dd")))
                        {
                            dic[n.ToString("yyyy-MM-dd")].Add(item.Shy);
                        }
                        else
                        {
                            dic.Add(n.ToString("yyyy-MM-dd"), new List<string>() { item.Shy });
                        }
                    }
                }

                var sb = new StringBuilder();
                sb.Append('[');
                foreach (var item in dayList)
                {
                    var iscurr = item.Substring(0, 7) == requestObject.QueryConditions[0].Content ? "1" : "0";
                    if (dic.ContainsKey(item))
                    {
                        var currValue = dic[item];                        
                        sb.Append($"{{");
                        sb.Append($"date:'{item.Substring(5)}',");
                        sb.Append($"shy:'{string.Join(',', dic[item])}',");
                        sb.Append($"currMonth: {iscurr}");
                        sb.Append($"}},");
                    }
                    else
                    {
                        sb.Append($"{{");
                        sb.Append($"date:'{item.Substring(5)}',");
                        sb.Append($"shy:'',");
                        sb.Append($"currMonth: {iscurr}");
                        sb.Append($"}},");
                    }
                    
                }
                sb.Append(']');
                var result = JsonConvert.DeserializeObject<dynamic>(sb.ToString());
                //返回执行结果
                return ResponseUtil<dynamic>.SuccessResult(result, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<dynamic>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 获取xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<dynamic>> GetProInfoAsync(RequestGet requestObject)
        {
            try
            {
                RefAsync<int> totalNumber = -1;//总记录数
                var day = Convert.ToDateTime($"{DateTime.Now.Year}-{requestObject.QueryConditions[0].Content}");
                var query = _db.Instance.Queryable<XmglxmxxpcDbModel,XmglxmxxDbModel,XmjckhxxDbModel,XmjcgltxDbModel>(
                    (t,t1,t2,t3) => new object[]
                    {
                        JoinType.Left , t.Xmid == t1.ID ,
                        JoinType.Left , t1.Khid == t2.ID ,
                        JoinType.Left , t1.Txid == t3.ID
                    });
                //查询未删除数据
                query.Where((t,t1,t2,t3) => t.Deleteflag == 0 && t.Kssj <= day && t.Jssj >= day);
                query.OrderBy((t,t1,t2,t3) => t.Xmid , OrderByType.Asc);


                var data = await query.Select(
                    (t,t1,t2,t3) => new
                    {
                        t.Shy,
                        t2.Khmc,
                        t3.Txmc,
                        t1.Shlx,
                        t.Kssj,
                        t.Jssj,
                        t.Rt
                    })
                    .ToListAsync();


                
                var sb = new StringBuilder();
                sb.Append('[');
                foreach (var item in data)
                {
                    sb.Append($"{{");
                    sb.Append($"khmc:'{item.Khmc}',");
                    sb.Append($"shy:'{item.Shy}',");
                    sb.Append($"txmc: '{item.Txmc}',");
                    sb.Append($"shlx: '{item.Shlx}',");
                    sb.Append($"ksrq: '{item.Kssj:yyyy-MM-dd}',");
                    sb.Append($"jsrq: '{item.Jssj:yyyy-MM-dd}',");
                    sb.Append($"rt: '{item.Rt}',");
                    sb.Append($"}},");
                }
                sb.Append(']');
                var result = JsonConvert.DeserializeObject<dynamic>(sb.ToString());
                //返回执行结果
                return ResponseUtil<dynamic>.SuccessResult(result, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<dynamic>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 新增xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PostAsync(RequestPost<XmglxmxxpcAddModel> requestObject)
        {
            var currDb = _db.Instance;
            try
            {
                //如果没有新增数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");

                currDb.BeginTran();
                
                //新增排程信息
                var xmids = requestObject.PostDataList.Select(p => p.Xmid).Distinct().ToList();
                //删除原有的排程信息
                await currDb.Deleteable<XmglxmxxpcDbModel>()
                    .Where(p => xmids.Contains(p.Xmid))
                    .ExecuteCommandAsync();
                var lclist = await currDb.Queryable<XmglxmxxlcDbModel>().Where(p => xmids.Contains(p.Xmid)).ToListAsync();
                foreach (var item in requestObject.PostDataList)
                {
                    if (item.Xmlcid != 0)
                        continue;
                    var lcxx = lclist.Where(p => p.Xmid == item.Xmid && p.Lcmc == item.Lcmc).FirstOrDefault();
                    if (lcxx == null)
                    {
                        var xmxx = await currDb.Queryable<XmglxmxxDbModel>().Where(p => p.ID == item.Xmid).FirstAsync();
                        currDb.RollbackTran();
                        return ResponseUtil<bool>.FailResult(false, $"{xmxx.Erpbh}没有设置'{xmxx.Shlx}'的流程模板信息");
                    }
                        
                    item.Xmlcid = lcxx.ID;
                }
                var insertList = _mapper.Map<List<XmglxmxxpcDbModel>>(requestObject.PostDataList);
                await currDb.Insertable(insertList).ExecuteCommandAsync();

                //更新流程表中的排程信息
                var oldlcid = 0;
                foreach(var item in insertList)
                {
                    if(oldlcid == 0 || oldlcid != item.Xmlcid)
                    {
                        oldlcid = item.Xmlcid;
                    }
                    else
                    {
                        continue;
                    }

                    var shts = insertList.Where(p => p.Xmlcid == item.Xmlcid).Sum(p => p.Rt);
                    var ksrq = insertList.Where(p => p.Xmlcid == item.Xmlcid).Min(p => p.Kssj);
                    var jsrq = insertList.Where(p => p.Xmlcid == item.Xmlcid).Max(p => p.Jssj);
                    var shy = string.Join(',', insertList.Where(p =>p.Xmlcid == item.Xmlcid).Select(p => p.Shy));
                    var shyid = string.Join(',', insertList.Where(p => p.Xmlcid == item.Xmlcid).Select(p => p.Shyid));

                    await currDb.Updateable<XmglxmxxlcDbModel>()
                        .SetColumns(p => p.Ksrq == ksrq)
                        .SetColumns(p => p.Jsrq == jsrq)
                        .SetColumns(p => p.Shts == (decimal)shts)
                        .SetColumns(p => p.Shy == shy)
                        .SetColumns(p => p.Shyid == shyid)
                        .SetColumns(p => p.Pcr == requestObject.PostDataList[0].Createname)
                        .SetColumns(p => p.Pcsj == DateTime.Now)
                        .Where(p => p.Xmid == requestObject.PostDataList[0].Xmid && p.ID == item.Xmlcid)
                        .ExecuteCommandAsync();
                }

                currDb.CommitTran();
                //返回执行结果
                return ResponseUtil<bool>.SuccessResult(true);
            }
            catch(Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 修改xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PutAsync(RequestPut<XmglxmxxpcEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxpcDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxpcDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .IgnoreColumns(p => new { p.Createid, p.Createtime,p.Createname })
                        .ExecuteCommandAsync() > 0;
                }
                
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
        /// <summary>
        /// 删除xm_gl_xmxxpc数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DeleteAsync(RequestDelete<DeleteModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有删除数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData、PostDataList不能都为null");
                //批量删除的优先级高于单记录删除
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量删除
                    var ids = requestObject.PostDataList.Select(p => p.ID);
                    result = await _db.Instance.Updateable<XmglxmxxpcDbModel>()
                            .SetColumns(p => p.Deleteflag == 1)
                            .Where(p => ids.Contains(p.ID))
                            .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录删除
                    result = await _db.Instance.Updateable<XmglxmxxpcDbModel>()
                        .SetColumns(p => p.Deleteflag == 1)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "删除数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
    }
}
